package com.booza.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.booza.constants.DatabaseConstants;
import com.booza.model.Country;
import com.booza.model.State;

/**
 * The hibernate DAO class for the domain Country.
 * 
 * @see CountryDAO
 */
@Transactional
public class CountryDAOImpl implements CountryDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	public void create(Country cntry)
	{
		Session session = sessionFactory.getCurrentSession();
		session.save(cntry);
	}

	@SuppressWarnings("unchecked")
	public List<Country> fetchAll()
	{
		return (List<Country>) sessionFactory.getCurrentSession().createCriteria(Country.class).addOrder(Order.asc("name"))
				.list();
	}

	public void update(Country cntry)
	{
		sessionFactory.getCurrentSession().update(cntry);
	}

	public Country findCountryById(String id)
	{
		//TODO THIS METHOD HAS ERROR.
		return (Country) sessionFactory.getCurrentSession().createCriteria(Country.class).add(
				Restrictions.eq(DatabaseConstants.COUNTRY_ID, id));
	}

	@SuppressWarnings("unchecked")
	public Collection<State> findStates()
	{
		return (List<State>) sessionFactory.getCurrentSession().createCriteria(State.class).list();
	}
}
